<template>
  <div class="app-container">

    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加API
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :default-expand-all="false"
      row-key="_id"
    >
      <!-- <el-table-column label="ID" prop="id" sortable="custom" align="center" min-width="160px">
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="名称" align="left">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="访问路径" align="center">
        <template slot-scope="{row}">
          <span>{{ row.path }}</span>
        </template>
      </el-table-column>

      <el-table-column label="api请求方式" align="center">
        <template slot-scope="{row}">
          <span>{{ row.method }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属分组" align="center">
        <template v-if="row.parent" slot-scope="{row}">
          <span>{{ apisOjb[row.parent] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="130" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="temp.type">
            <el-radio-button label="GROUP">组</el-radio-button>
            <el-radio-button label="REQUEST">请求</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <template v-if="temp.type === 'REQUEST'">
          <el-form-item label="请求路径" prop="path">
            <el-input v-model="temp.path" />
          </el-form-item>

          <el-form-item label="请求方式" prop="method">
            <el-radio-group v-model="temp.method">
              <el-radio label="GET">GET</el-radio>
              <el-radio label="POST">POST</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <el-form-item label="所属组" prop="parent">
          <el-cascader
            v-model="temp.parent"
            :options="apiTreeWithoutRequestData"
            :props="cascaderProps"
            :show-all-levels="true"
            clearable
            @change="handleChange"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showReviewer: false,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      temp: {
        _id: '',
        title: '', // 名称
        type: 'GROUP', //  组/请求
        parent: '', // 上级
        path: '', // 浏览器访问路径
        method: 'GET' // 请求方式
      },
      apiTreeWithoutRequestData: [],
      cascaderProps: {
        value: '_id',
        label: 'title',
        children: 'children',
        emitPath: false,
        checkStrictly: true
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑API',
        create: '创建API'
      },
      rules: {
        title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        path: [{ required: true, message: '浏览器访问路径不能为空', trigger: 'blur' }],
        method: [{ required: true, message: '请求方式不能为空', trigger: 'blur' }]
      },
      apisOjb: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange(value) {
      console.log(value)
    },
    getList() {
      this.listLoading = true
      this.$api.getApiListApi().then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.apisOjb = response.data.objData
        Object.keys(this.apisOjb).forEach(key => {
          this.apisOjb[key] = this.apisOjb[key].title
        })
        this.listLoading = false
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$api.getApiTreeWithoutRequestApi().then(response => {
        this.apiTreeWithoutRequestData = response.data.items
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    resetTemp() {
      this.temp = {
        _id: '',
        title: '', // 名称
        path: '', // 浏览器访问路径
        method: 'GET', // 请求方式
        type: 'REQUEST',
        parent: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$api.createApiApi(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: 'API添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.$api.getApiTreeWithoutRequestApi().then(response => {
        this.apiTreeWithoutRequestData = response.data.items
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log("🚀 ~ file: api.vue ~ line 241 ~ this.$refs['dataForm'].validate ~ tempData", tempData)
          this.$api.updateAPIApi(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$api.removeApiApi(row).then((data) => {
        this.getList()
        this.$notify({
          title: data.message,
          message: '',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
